#include "AccusationView.h"

#include <boost/bind.hpp>
#include "../../models/network/CardSetViewModel.h"
#include "../../../utils/LateEvents.hpp"
#include "../../../domain/configuration/NetworkConfiguration.h"

using namespace Views::Server;
using namespace Utils;

AccusationView::AccusationView(Domain::Network::GameServer* server, Utils::GUI::Form* form,
	Players::Player* player, Players::Player* current_player)
	: Graphic::AccusationView(form), server(server), server_owner(player), current_player(current_player)
{
}

void AccusationView::askIfPlayerWantsToPerformAccusation()
{
	if (current_player == server_owner)
	{
		Graphic::AccusationView::askIfPlayerWantsToPerformAccusation();
	}
	else
	{
		server->doOnReceiveData(Domain::Configuration::Network::ACCUSATION_DECISION,
			boost::bind(&AccusationView::onDecisionSet, this, _1, _2));
	}
}

void AccusationView::onDecisionSet(bool decision)
{
	sf::Packet packet;
	packet << decision;
	server->sendToAll(Domain::Configuration::Network::ACCUSATION_DECISION, packet);
	Graphic::AccusationView::onDecisionSet(decision);
}

void AccusationView::onDecisionSet(Domain::Network::PlayerClient* player_client, sf::Packet packet)
{
	if (player_client->getPlayer() == current_player)
	{
		sf::Packet packet_copy = packet;
		bool decision;
		packet >> decision;
		server->sendToAll(Domain::Configuration::Network::ACCUSATION_DECISION, packet_copy);
		LateAppLoopEventFactory::create<OnPlayerDecisionSet, bool>(
			&OnPlayerDecisionSet::operator(), &playerDecisionSetEvent)(decision);
	}
}

void AccusationView::askForCardsInAccusation(Cards::CardsCollection cards)
{
	if (current_player == server_owner)
	{
		Graphic::AccusationView::askForCardsInAccusation(cards);
	}
	else
	{
		all_cards = cards;
		server->doOnReceiveData(Domain::Configuration::Network::ACCUSATION_CARDS,
			boost::bind(&AccusationView::onCardsSet, this, _1, _2));
	}
}

void AccusationView::onCardsSet(Cards::CardSet cards)
{
	sf::Packet packet;
	Views::Models::Network::CardSetViewModel csvm(cards);
	packet << csvm;
	server->sendToAll(Domain::Configuration::Network::ACCUSATION_CARDS, packet);
	Graphic::AccusationView::onCardsSet(cards);
}

void AccusationView::onCardsSet(Domain::Network::PlayerClient* player_client, sf::Packet packet)
{
	if (player_client->getPlayer() == current_player)
	{
		sf::Packet packet_copy = packet;
		Views::Models::Network::CardSetViewModel csvm(all_cards);
		packet >> csvm;
		server->sendToAll(Domain::Configuration::Network::ACCUSATION_CARDS, packet);
		cardsInAccusationSetEvent(csvm.card_set);
	}
}

